package com.rambo.dsd.base.handler;


import org.apache.wss4j.common.ext.WSPasswordCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * cxf 服务端安全验证
 * 密钥方式 USERNAME_TOKEN/密钥方式SIGNATURE
 * 值必须和客户端设的值相同,从cxf2.4.x后校验方式改为cxf内部实现校验，不必自己比较password是否相同
 * 请参考：http://cxf.apache.org/docs/24-migration-guide.html的Runtime
 */
public class CXFServerAuthHandler implements CallbackHandler {
    protected final static Logger log = LoggerFactory.getLogger(CXFServerAuthHandler.class);
    private static final Map<String, String> userMap = new HashMap<String, String>();

    static {
        userMap.put("webappA", "webappA2017");
        userMap.put("webappB", "webappB2017");
    }

    @Override
    public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
        for (Callback callback : callbacks) {
            WSPasswordCallback pc = (WSPasswordCallback) callback;

            String clientUsername = pc.getIdentifier();
            String serverPassword = userMap.get(clientUsername);
            log.info(" client:{} is starting webservice...", clientUsername);
            int usage = pc.getUsage();
            if (usage == WSPasswordCallback.USERNAME_TOKEN) {
                pc.setPassword(serverPassword);
            } else if (usage == WSPasswordCallback.SIGNATURE) {
                pc.setPassword(serverPassword);
            }
        }
    }
}